# -*- coding: utf-8 -*-
import requests
import json
from login_auth_data import all_auth_data, c_liepin, tdvideo, lpt, old_lebanban, cdcc

requests.packages.urllib3.disable_warnings()


def get_cookie(auth_data):
    # 获取各业务线passport对应的cookie
    headers = {"X-Requested-With": "XMLHttpRequest"}
    auth_resp = requests.get(url=auth_data, headers=headers, verify=False)
    cookie = ''
    for i in auth_resp.cookies:
        if cookie == '':
            cookie = cookie + str(i).split()[1]
        else:
            cookie = cookie + '; ' + str(i).split()[1]
    print(cookie)
    return cookie

def addtarget(domain):
    # 添加扫描目标，返回目标的target_id
    data = {"address": 'https://' + domain, "description": domain, "criticality": "10"}
    try:
        response = requests.post(wvsserver + "/api/v1/targets", data=json.dumps(data), headers=wvs_headers, verify=False)
        result = json.loads(response.content)
        return result['target_id']
    except Exception as e:
        print(e)
        return

def settarget(domain, target_id, domain_cookie):
    # 根据target_id对扫描目标进行爬虫和高级配置
    url = wvsserver + "api/v1/targets/" + target_id + "/configuration"
    data = {"limit_crawler_scope": True, "case_sensitive": "auto", "excluded_paths": ["/v1/logout.*"], "user_agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.21 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.21"}
    data2 = '{"issue_tracker_id":"","technologies":[],"custom_headers":["X-Requested-With: XMLHttpRequest"],"custom_cookies":[{"url":"' + 'https://' + domain + '","cookie":"' + domain_cookie + '"}],"debug":false,"excluded_hours_id":""}'
    try:
        requests.patch(url, data=json.dumps(data), headers=wvs_headers, verify=False)  # 爬虫配置
        requests.patch(url, data=data2, headers=wvs_headers, verify=False)  # 高级配置，包括cookie
    except Exception as e:
        print(e)
        return

def setscan(target_id):
    # 根据target_id开始扫描,返回扫描id
    data = {"target_id": target_id, "profile_id": "11111111-1111-1111-1111-111111111111",
            "schedule": {"disable": False, "start_date": None, "time_sensitive": False}}
    try:
        response = requests.post(wvsserver + "/api/v1/scans", data=json.dumps(data), headers=wvs_headers, verify=False)
        result = response.headers
        scan_id = result['Location'].split('/')[4]
        return scan_id
    except Exception as e:
        print(str(e))
        return

def scantask(domain):
    # if url have cookie:
    #     domain_cookie = get_cookie(auth_data)
    #     target_id = addtarget(domain)
    #     settarget(domain, target_id, domain_cookie)
    #     setscan(target_id)
    # else:
    #     target_id = addtarget(domain)
    #     settarget_no_cookie(target_id)
    #     setscan(target_id)


    target_id = addtarget(domain)
    settarget(domain, target_id, domain_cookie)
    setscan(target_id)


if __name__ == "__main__":
    wvsserver = "https://127.0.0.1:3443/"
    apikey = "1986ad8c0a5b3df4d7028d5f3c06e936c3838632afd454321a9bf8e64ca3fc9ea"
    wvs_headers = {"X-Auth": apikey, "content-type": "application/json"}

    # 读取json数据
    # with open('login_auth_data.py', 'r', encoding='utf-8') as f:
    #     login_data_list = json.loads(f.read())
    # print(login_data_list)
    # 获取每个域名进行扫描
    # with open('awvs.txt', 'r') as file:
    #     url_list = file.read().splitlines()
    # for domain in url_list:
    #     scantask(domain)

    for i in all_auth_data:
        # if i["business"] == "c_liepin":
        #     domain_cookie = get_cookie(i["auth_domain"])
        #     for domain in c_liepin:
        #         scantask(domain)
        # elif i["business"] == "tdvideo":
        #     domain_cookie = get_cookie(i["auth_domain"])
        #     print(i["business"], domain_cookie)
        #     for domain in tdvideo:
        #         scantask(domain)
        if i["business"] == "lpt":
            domain_cookie = get_cookie(i["auth_domain"])
            print(i["business"], domain_cookie)
            for domain in lpt:
                scantask(domain)
        # elif i["business"] == "old_lebanban":
        #     domain_cookie = get_cookie(i["auth_domain"])
        #     print(i["business"], domain_cookie)
        #     for domain in old_lebanban:
        #         scantask(domain)
        # elif i["business"] == "cdcc":
        #     domain_cookie = get_cookie(i["auth_domain"])
        #     print(i["business"], domain_cookie)
        #     for domain in cdcc:
        #         scantask(domain)
        else:
            print("扫描任务全部提交完成")

